<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');
/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{
    public $uses = array('AuthenticatedApp');
    public $components = array(
        'RequestHandler','ExcelPHP','Session','Message'
    );

    /**
     * Function for return json from given array.
     * @author Anoop  P.R.
     * @param  array  $json_data
     * @return json
     */
    protected function _response($json_data = array()) {
        return new CakeResponse(array('type' => 'json', 'body' => json_encode($json_data)));
    }

    public function beforeFilter() {
        $this->autoRender = false;

        // check app is providing authentication information
        if( !$this->isAppAuthenticated() ) {
            echo $this->_response(array('response_code' => 1, 'message' => 'Application Not Authenticated','data'=>array()));
            exit;
        }
    }

    private function isAppAuthenticated() {

        // add simple bypass protocol for apps that need to get into this webservice without authentication
       // if( isset($_GET['no_auth']) /*&& $_GET['no_auth'] == base64_decode('webservice')*/ ) {
           // return true;
       // }

        // else check for app authentication session
        if( $this->Session->check('appAuth') && $this->Session->read('appAuth') == $_SERVER['REMOTE_ADDR'] ) {
            return true;
        }

        // if not authenticated, try authentication process
        if( isset($this->request->data['APP_KEY']) ) {
            $app_id = $this->request->data['APP_ID'];
            $app_key = $this->request->data['APP_KEY'];

            if( $this->AuthenticatedApp->authenticate($app_id, $app_key) ) {
                $this->Session->write('appAuth', $_SERVER['REMOTE_ADDR']);
                return true;
            }
        }

        // return false if none of the above is provided
        return false;
    }




    function formatNumber($value = 0, $type = 'number', $decimal_place = 2)
    {
        if ($type == 'money') {
            $num = number_format($value, $decimal_place, '.', ',');
        } else {
            $num = number_format($value, $decimal_place, '.', '');
        }

        return $num;
    }

    function randomString($length)
    {
        $original_string = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'), array(time()));
        $original_string = implode("", $original_string);
        return substr(str_shuffle($original_string), 0, $length);
    }

    function convertDate($date = null, $type = 'mysql')
    {
        $res = '';
        if ($type == 'mysql') {
            $res = date("Y-m-d", strtotime($date));
        } elseif ($type == 'mysql_flip') {
            $res = date("d-m-Y", strtotime($date));
        }
        elseif ($type == 'ui') {
            $res = date("F d, Y", strtotime($date));
        }
        elseif ($type == 'ui_short') {
            $res = date("F, Y", strtotime($date));
        }
        elseif ($type == 'formal') {
            $res = date("m/d/Y", strtotime($date));
        }
        return $res;
    }


    protected function convertToExcel($list_headers, $param, $filename)
    {
        ini_set("memory_limit", "512M");
        set_time_limit('1200');

        $company_profile = $this->global_company;

        $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
        $cacheSettings = array(' memoryCacheSize ' => '8MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Interpay")
            ->setLastModifiedBy("Interpay")
            ->setTitle("Office 2007 XLSX Interpay Document")
            ->setSubject("Office 2007 XLSX Interpay Document")
            ->setDescription("Interpay document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Interpay result file");

        // Set default font
        $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);

        $count_h = 1;
        foreach ($list_headers as $header) {
            $letter_h = $this->getAlphabetCharacter($count_h);
            $objPHPExcel->getActiveSheet()->setCellValue($letter_h . '1', $header);
            $count_h++;
        }
        //Bold the headers
        $letter_h = $this->getAlphabetCharacter($count_h - 1);
        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $letter_h . '1')->getFont()->setBold(true);

        $it = 2;
        foreach ($param as $item) {
            $count_inner = 1;
            foreach ($item as $itm) {
                $letter_h = $this->getAlphabetCharacter($count_inner);
                $objPHPExcel->getActiveSheet()->setCellValue($letter_h . $it, strip_tags($itm));
                $count_inner++;
            }
            $it++;
        }
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Page_1');


        $objPHPExcel->setActiveSheetIndex(0);

        return array(
            'excel_obj' => $objPHPExcel,
            'filename' => $filename
        );
    }

    function getAlphabetCharacter($index)
    {
        $alphabet = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P'
        , 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');
        return $alphabet[$index];
    }

    /**
     * Function for validating the input parameters.
     * @author Anoop  P.R.
     * @param  array  $rules
     * @param  array  $data
     */
    protected function _validateParams($rules = array(), $data = array()) {
        $error = false;
        $errorMsg = array();
        foreach ($rules as $rule => $fields) {

            if(trim($rule) == 'required') {
                $response = $this->__checkRequired($fields, $data);
                if($response['status'] == 'failed') {
                    $error = true;
                    $errorMsg = array_merge($errorMsg, $response['msg']);
                }
            }

            if(trim($rule) == 'numeric') {
                $response = $this->__checkNumeric($fields, $data);
                if($response['status'] == 'failed') {
                    $error = true;
                    $errorMsg = array_merge($errorMsg, $response['msg']);
                }
            }
        }
        if (!$error) {
            return "NO_ERROR";
        } else {
            $response = array(
                "msg" => "Invalid parameter Passed.",
                "details" => $errorMsg
            );
            return $this->_response($response);
        }
    }

    /**
     * [__checkRequired description]
     * @author Anoop P R
     * @param  string $fields
     * @param  array  $data
     * @return boolean
     */
    private function __checkRequired($fields='', $data = array()) {
        if(empty($fields)) {
            return array(
                'status' => 'failed',
                'msg' => array('Required fields list not found.')
            );
        }
        $output = array();
        $params = explode(',', $fields);
        foreach($params as $field) {
            if(!isset($data[trim($field)]) || $data[trim($field)] == "") {
                $output[] = 'Input parameter \''. trim($field) .'\' is missing';
            }

            if(isset($data['key']) && trim($field) == 'key') {
                $validKeys = $this->ApiKey->getApiKeys();
                if(!in_array($data[trim($field)], $validKeys)) {
                    $output[] = "Not a valid API key";
                }
            }
        }
        if(empty($output)) {
            return array(
                'status' => 'success',
                'msg' => 'NO_ERROR'
            );
        } else {
            return array(
                'status' => 'failed',
                'msg' => $output
            );
        }
    }

    /**
     * [__checkNumeric description]
     * @author Anoop P R
     * @param  string $fields
     * @param  array  $data
     * @return boolean
     */
    private function __checkNumeric($fields='', $data = array()) {
        if(empty($fields)) {
            return array(
                'status' => 'failed',
                'msg' => array('Required fields list not found.')
            );
        }
        $output = array();
        $params = explode(',', $fields);
        foreach ($params as $field) {
            if(!empty($data[trim($field)]) && !is_numeric($data[trim($field)])) {
                $output[] = 'Parameter \''. trim($field) .'\' should be numeric.';
            }
        }
        if(empty($output)) {
            return array(
                'status' => 'success',
                'msg' => 'NO_ERROR'
            );
        } else {
            return array(
                'status' => 'failed',
                'msg' => $output
            );
        }
    }
}